package com.ht.controller;

import com.ht.core.AjaxResult;
import com.ht.entity.SimpleFlight;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author guoyuxing
 * @date 2025/5/8 13:32
 */
@RestController
@RequestMapping("flight/")
public class SimpleFightController {
    private List<SimpleFlight> sfList;

    public SimpleFightController(){
        sfList = new ArrayList<>();
        //sfList.add(new SimpleFlight("1001","str"));
    }

    @GetMapping("getById")
    public AjaxResult getById(String id){
        Optional<SimpleFlight> first = sfList.stream().filter(s -> s.getId().equals(id)).findFirst();
        return first.isPresent() ? AjaxResult.success(first.get()) : AjaxResult.error("未找到ID"+id+"对应的数据！");
    }

    @GetMapping("getById2")
    public AjaxResult getById2(String id){
        Optional<SimpleFlight> first = sfList.stream().filter(s -> s.getId().equals(id)).findFirst();
        if(!first.isPresent())
            return AjaxResult.error("未找到ID"+id+"对应的数据！");
        //return first.isPresent() ? AjaxResult.success(first.get()) : AjaxResult.error("未找到ID"+id+"对应的数据！");
        Map<String,Object> map = new HashMap<>();
        map.put("id",first.get().getId());
        map.put("data",first.get().getStr()); 
        return AjaxResult.success(map);
    }

    @GetMapping("getList")
    public AjaxResult getList(){
        return AjaxResult.success(sfList);
    }

    @PostMapping("add")
    public AjaxResult add(@RequestBody SimpleFlight simpleFlight){
        Optional<SimpleFlight> first = sfList.stream().filter(s -> s.getId().equals(simpleFlight.getId())).findFirst();
        return first.isPresent() ? AjaxResult.error("ID为"+simpleFlight.getId()+"的数据已经存在，添加失败!") : AjaxResult.success(sfList.add(simpleFlight));
    }

    @PostMapping("update")
    public AjaxResult update(@RequestBody SimpleFlight simpleFlight){
        for (int i = 0; i < sfList.size(); i++) {
            if(sfList.get(i).getId().equals(simpleFlight.getId())){
                sfList.set(i,simpleFlight);
            }
        }
        return AjaxResult.success(sfList);
    }

    @GetMapping("deleteById")
    public AjaxResult deleteById(String id){
        Optional<SimpleFlight> first = sfList.stream().filter(s -> s.getId().equals(id)).findFirst();
        return  first.isPresent() ? AjaxResult.success(sfList.remove(first.get())) : AjaxResult.error("未找到ID"+id+"对应的数据！");
    }

}
